package com.ruoyi.web.controller.fx;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.dto.FxStoreGoodDto;
import com.ruoyi.system.domain.dto.FxSupplierGoodDto;
import com.ruoyi.system.domain.fx.FxGoodclassify;
import com.ruoyi.system.domain.fx.FxStoreGood;
import com.ruoyi.system.domain.fx.FxSupplierGood;
import com.ruoyi.system.domain.vo.FxStoreGoodVo;
import com.ruoyi.system.domain.vo.FxSupplierGoodMtVO;
import com.ruoyi.system.service.fx.IFxStoreGoodService;
import com.ruoyi.system.service.fx.IFxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 店铺商品Controller
 *
 * @author ruoyi
 * @date 2024-07-23
 */
@RestController
@RequestMapping("/fx/store/good")
public class FxStoreGoodController extends BaseController {
    @Autowired
    private IFxStoreGoodService fxStoreGoodService;

    @Autowired
    private IFxUserService iFxUserService;



    /**
     * 查询店铺商品列表
     */
    @GetMapping("/list")
    public TableDataInfo list(FxStoreGoodDto dto) {
        // 获取当前登录人id
        Long userId =  SecurityUtils.getUserId();
        List<Long> roles = SecurityUtils.getLoginUser().getUser().getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList());
        dto.setUserId(userId);
        if (roles.contains(1L) || roles.contains(6L)) {
            dto.setUserId(null);
        }
        startPage();
        List<FxStoreGoodVo> list = fxStoreGoodService.selectStoreGoodList(dto);
        return getDataTable(list);
    }



    /**
     * 查询店铺商品列表
     */
    @GetMapping("/getStoreGoodList")
    public TableDataInfo getStoreGoodList(FxStoreGoodDto dto) {
        // 获取当前登录人id
        Long userId =  SecurityUtils.getUserId();
        List<Long> roles = SecurityUtils.getLoginUser().getUser().getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList());
        dto.setUserId(userId);
        if (roles.contains(1L) || roles.contains(6L)) {
            dto.setUserId(null);
        }
        startPage();
        List<FxStoreGoodVo> list = fxStoreGoodService.getStoreGoodList(dto);
        return getDataTable(list);
    }


    /**
     * 导出商品
     */
    @Log(title = "导出商品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(FxStoreGoodDto dto,HttpServletResponse response) {
        //复制上面的查询
        Long userId =  SecurityUtils.getUserId();
        List<Long> roles = SecurityUtils.getLoginUser().getUser().getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList());
        dto.setUserId(userId);
        if (roles.contains(1L) || roles.contains(6L)) {
            dto.setUserId(null);
        }
        List<FxStoreGoodVo> list = fxStoreGoodService.selectStoreGoodList(dto);
        //将id当做key转换为map
        List<FxSupplierGoodMtVO> fxSupplierGoodMtVOS = BeanUtil.copyToList(list, FxSupplierGoodMtVO.class);

        Map<Long, FxStoreGoodVo> map = list.stream().collect(Collectors.toMap(FxStoreGoodVo::getId, t -> t));
        //遍历查询结果
        for (FxSupplierGoodMtVO fxSupplierGoodMtVO : fxSupplierGoodMtVOS) {
            //如果是主商品 将规格名称 改为 商品名称
            if (ObjectUtils.isEmpty(fxSupplierGoodMtVO.getParentId())||fxSupplierGoodMtVO.getParentId().equals(0L)){
                fxSupplierGoodMtVO.setSonGoodName(fxSupplierGoodMtVO.getGoodName());
                //如果是字商品 将商品名称 改为 父商品商品名称
            }else if (map.containsKey(fxSupplierGoodMtVO.getParentId())){
                FxStoreGoodVo father = map.get(fxSupplierGoodMtVO.getParentId());
                String itemGoodName=fxSupplierGoodMtVO.getGoodName();
                fxSupplierGoodMtVO.setGoodName(father.getGoodName());
                fxSupplierGoodMtVO.setSonGoodName(itemGoodName);
            }
        }
        fxSupplierGoodMtVOS.sort(Comparator.comparing(FxSupplierGoodMtVO::getGoodName));
        ExcelUtil<FxSupplierGoodMtVO> util = new ExcelUtil<>(FxSupplierGoodMtVO.class);
        util.exportExcel(response,fxSupplierGoodMtVOS, "店铺商品");
    }

    /**
     * 导入店铺商品
     */
    @Log(title = "导入店铺商品", businessType = BusinessType.EXPORT)
    @PostMapping("/importDp")
    public void importDp(@RequestPart MultipartFile file, HttpServletResponse response) {
        fxStoreGoodService.importDp(file,response);
    }



    @GetMapping("/getLeftClassifyByStoreId")
    public AjaxResult getLeftClassifyByStoreId(FxStoreGood fxStoreGood) {
        // List<FxGoodclassify> list = fxStoreGoodService.selectLeftClassify(fxStoreGood);
        //  return success(list);
        List<FxGoodclassify> list = fxStoreGoodService.getLeftClassifyByStoreId(fxStoreGood.getStoreId());
        return success(list);
    }
    /**
     * 小程序 店铺商品
     *
     * @param fxStoreGood
     * @return
     */
    @GetMapping("/classifyList")
    public AjaxResult classifyList(FxStoreGood fxStoreGood) {
        // List<FxGoodclassify> list = fxStoreGoodService.selectLeftClassify(fxStoreGood);
       //  return success(list);
        List<FxGoodclassify> list = fxStoreGoodService.selectLeftClassifyByStoreId(fxStoreGood.getStoreId());
        for (FxGoodclassify fxGoodclassify : list) {
            List<FxStoreGoodVo> goodList = fxGoodclassify.getGoodList();
            if (!CollectionUtils.isEmpty(goodList)){
                List<FxStoreGoodVo> collect = goodList.stream().filter(item -> !CollectionUtils.isEmpty(item.getGoodsList())).collect(Collectors.toList());
                fxGoodclassify.setGoodList(collect);
            }
        }
        return success(list);
    }

    /**
     * 小程序门店商品 （未启用）
     *
     * @param fxStoreGood
     * @return
     */
//    @GetMapping("/mapApp")
    public AjaxResult mapApp(FxStoreGood fxStoreGood) {
        Map<Long, List<FxStoreGoodVo>> list = fxStoreGoodService.selectFxStoreGoodMap(fxStoreGood);
        return success(list);
    }

    /**
     * 门店详情商品列表（app）未启用
     *
     * @param fxStoreGood
     * @return
     */
//    @GetMapping("/listApp")
    public AjaxResult listApp(FxStoreGood fxStoreGood) {
        List<FxGoodclassify> list = fxStoreGoodService.selectFxStoreGoodListTree(fxStoreGood);
        return success(list);
    }

    /**
     * 小程序搜索商品
     *
     * @param dto
     * @return
     */
    @GetMapping("/searchGood")
    public AjaxResult searchGood(FxStoreGoodDto dto) {
        List<FxStoreGoodVo> list = fxStoreGoodService.selectAppGoodList(dto);
        return success(list);
    }

//    /**
//     * 导出店铺商品列表
//     */
//    @Log(title = "店铺商品", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, FxStoreGoodDto dto) {
//        List<FxStoreGoodVo> list = fxStoreGoodService.selectStoreGoodList(dto);
//        ExcelUtil<FxStoreGoodVo> util = new ExcelUtil<FxStoreGoodVo>(FxStoreGoodVo.class);
//        util.exportExcel(response, list, "店铺商品数据");
//    }

    /**
     * 获取店铺商品详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(fxStoreGoodService.selectFxStoreGoodById(id,null));
    }

    /**
     * 获取店铺商品详细信息
     */
    @GetMapping(value = "/getGoodsById")
    public AjaxResult getGoodsById(Long id, Long goodsId, Long storeId) {
        FxStoreGoodVo good = fxStoreGoodService.getStoreGoodById(id, goodsId, storeId);
        return success(good);
    }

    /**
     * 获取店铺商品详情
     * @param supplierGoodId
     * @return
     */
    @GetMapping(value = "/supplier/{supplierGoodId}")
    public AjaxResult getGoodInfo(@PathVariable("supplierGoodId") String supplierGoodId) {
        Long aLong=null;
        try {
            aLong = Long.valueOf(supplierGoodId);
        }catch (Exception e) {
            throw new  GlobalException("商品id输入有误");
        }
        FxStoreGoodVo fxStoreGoodVo = fxStoreGoodService.selectFxStoreGoodById(null, aLong);
        if (fxStoreGoodVo.getIsInitiate().equals(1)){
            throw new  GlobalException("该商品还未上架请勿扫码");
        }
        return success(fxStoreGoodVo);
    }

    /**
     * 新增店铺商品
     */
    @Log(title = "店铺商品", businessType = BusinessType.INSERT)
//    @PostMapping
    public AjaxResult add(@RequestBody FxStoreGood fxStoreGood) {
        fxStoreGood.setCreateUser(Convert.toInt(getUserId()));
        return toAjax(fxStoreGoodService.insertFxStoreGood(fxStoreGood));
    }

    @Log(title = "新增店铺商品", businessType = BusinessType.INSERT)
    @PostMapping("/addGood")
    public AjaxResult addGood(@RequestBody FxSupplierGood fxSupplierGood) {
        int i = fxStoreGoodService.insertFxStoreGood(fxSupplierGood);
        if (!CollectionUtils.isEmpty(fxSupplierGood.getSonList())){
            for (FxSupplierGood good : fxSupplierGood.getSonList()) {
                good.setParentId(fxSupplierGood.getId());
                i += fxStoreGoodService.insertFxStoreGood(good);
            }
        }
        return toAjax(i);
    }



    /**
     * 修改店铺商品
     */
    @Log(title = "店铺商品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FxSupplierGoodDto fxSupplierGood) {
        int i = fxStoreGoodService.updateFxStoreGood(fxSupplierGood);

//        for (FxSupplierGood good : fxSupplierGood.getSonList()) {
//            if(good.getId() != null){
//                FxSupplierGoodDto goodDto = new FxSupplierGoodDto();
//                BeanUtils.copyProperties(good, goodDto);
//                i += fxStoreGoodService.updateFxStoreGood(goodDto);
//            }else {
//                good.setParentId(fxSupplierGood.getId());
//                i += fxStoreGoodService.insertFxStoreGood(good);
//            }
//        }
        return toAjax(i);
    }


    @Log(title = "店铺商品", businessType = BusinessType.UPDATE)
    @PutMapping("editAll")
    public AjaxResult editAll(@RequestBody List<FxSupplierGoodDto> fxSupplierGoodDtos) {
        return toAjax(fxStoreGoodService.editAll(fxSupplierGoodDtos));
    }



    @Log(title = "店铺商品审核", businessType = BusinessType.UPDATE)
    @PutMapping("/audit")
    public AjaxResult audit(@RequestBody FxSupplierGoodDto fxSupplierGood) {
        return toAjax(fxStoreGoodService.updateStoreGoodAudit(fxSupplierGood));
    }

    /**
     * 店铺商品上下架
     * @return
     */
    @GetMapping("/upOrDown")
    public AjaxResult upOrDown(FxStoreGoodDto dto) {
        return toAjax(fxStoreGoodService.upOrDown(dto));
    }

    /**
     * 补货
     * @param fxStoreGood
     * @return
     */
    @PostMapping("/replenishment")
    public AjaxResult replenishment(@RequestBody FxStoreGood fxStoreGood) {
        return toAjax(fxStoreGoodService.updateFxStoreGoodCounts(fxStoreGood));
    }

    /**
     * 删除店铺商品
     */
    @Log(title = "店铺商品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(fxStoreGoodService.updateDelFlag(ids));
    }
}
